package com.yngrp.controller.wo;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.DateUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSType;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.yngrp.entity.Holiday;
import com.yngrp.entity.Responsibler;
import com.yngrp.entity.Role2WoState;
import com.yngrp.entity.TodoWO;
import com.yngrp.entity.WoType;
import com.yngrp.entity.WorkAsso;
import com.yngrp.entity.WorkOrder;
import com.yngrp.entity.WorkProcess;
import com.yngrp.service.wo.WorkOrderService;
import com.yngrp.util.Constant;

/**
 * @Description: TODO(工单管理处理类)
 * @author  SLH
 * @date  20160716 
 */

@Controller
@RequestMapping("/woController")
public class WorkOrderController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(WorkOrderController.class);
	
	private SystemService systemService;
	
	private WorkOrderService workOrderService;

	@Autowired
	public void setSystemService(SystemService systemService) {
		this.systemService = systemService;
	}

	@Autowired
	public void setWorkOrderService(WorkOrderService workOrderService) {
		this.workOrderService = workOrderService;
	}
	
	/**
	 *  创建工单页面跳转
	 * 
	 *  @return
	 */
	@RequestMapping(params = "createWoR")
	public String createWoR(HttpServletRequest request) {
		setWoStateByRole(request);
		setWoType(request);
		return "com/yngrp/wo/createWo";
	}
	
	@RequestMapping(params = "create95598WoR")
	public String create95598WoR(HttpServletRequest request) {
		setWoStateByRole(request);
		setWoType(request);
		return "com/yngrp/wo/create95598Wo";
	}
	
	@RequestMapping(params = "createZZWoR")
	public String createZZWoR(HttpServletRequest request) {
		setWoStateByRole(request);
		setWoType(request);
		return "com/yngrp/wo/createZZWo";
	}
	
	/**
	 * 设置工单类型
	 * @param request
	 */
	private void setWoType(HttpServletRequest request){
        
        List<WoType> woTypeList = systemService.findHql("from WoType where platform='"+Constant.PLATFROM_SERVICE+"' order by sortNo asc");
        request.setAttribute("woTypeList", woTypeList);
	}
	
	/**
	 * 不同角色用户关联的工单操作状态
	 * @param request
	 */
	private void setWoStateByRole(HttpServletRequest request){
		TSUser user = ResourceUtil.getSessionUserName();
        String roleCode = user.getRoleCodes();
        
        List<Role2WoState> woStateList = workOrderService.getWoStateByRole( roleCode);
        request.setAttribute("woStateList", woStateList);
	}
	
	/**
	 * 保存工单
	 * 
	 * @param wo
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "saveWO")
	@ResponseBody
	public AjaxJson saveWO(WorkOrder wo, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		
		try{
			message = "工单创建成功！";
			workOrderService.saveWO(wo);
			systemService.addLog(message, Globals.Log_Type_INSERT,Globals.Log_Leavel_INFO);
			
			j.setMsg(message);
		}catch(Exception ex){
			message = "工单创建失败,请联系系统管理员！";
			systemService.addLog(message, Globals.Log_Type_INSERT,Globals.Log_Leavel_INFO);
			j.setMsg(message);
		}

		return j;
	}
	
	/**
	 *  工单管理页面跳转
	 * 
	 *  @return
	 */
	@RequestMapping(params = "woMgrR")
	public String woMgrR(HttpServletRequest request) {
		
		return "com/yngrp/wo/woMgr";
	}
	/**
	 * 删除工单
	 *
	 * @return
	 */
	@RequestMapping(params = "delWo")
	@ResponseBody
	public AjaxJson delWo( HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
	 
		//获取工单编号
		String wo_id = request.getParameter("wo_id");
		if(StringUtils.isNotEmpty(wo_id)){
			message = "删除成功";
			workOrderService.delWO(Integer.parseInt(wo_id));
			systemService.addLog("工单"+wo_id+message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			j.setMsg(message);
		}
		return j;
	}
	
	/***
	 * 历史工单查询
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param wo
	 */
	@RequestMapping(params = "historyWOGrid")
	public void historyWOGrid(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid, WorkOrder wo) {
		CriteriaQuery cq = new CriteriaQuery(WorkOrder.class, dataGrid);

		//联系人
        String contactMan = wo.getContactMan();
        if(StringUtils.isNotEmpty(contactMan)) {
        	contactMan = contactMan.trim();
        	if(contactMan.lastIndexOf("%")==-1){
        		contactMan = "%"+contactMan + "%";
            }
        	cq.like("contactMan", contactMan);
        }
        //客户名称
        String customerName = wo.getCustomerName();
        if(StringUtils.isNotEmpty(customerName)) {
        	customerName = customerName.trim();
        	if(customerName.lastIndexOf("%")==-1){
        		customerName = "%"+customerName + "%";
            }
        	cq.like("customerName", customerName);
        }
        //联系电话
        String contactPhone = wo.getContactPhone();
        if(StringUtils.isNotEmpty(contactPhone)) {
        	contactPhone = contactPhone.trim();
        	if(contactPhone.lastIndexOf("%")==-1){
        		contactPhone = "%"+contactPhone + "%";
            }
        	cq.like("contactPhone", contactPhone);
        }
        if(StringUtils.isEmpty(contactMan) && StringUtils.isEmpty(customerName) && StringUtils.isEmpty(contactPhone)){
        	cq.eq("customerNo", "-1");
        }
        cq.add();
        this.systemService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	
	/**
	 * 工单详情查看
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "woDetail")
	public ModelAndView woDetail(HttpServletRequest request) {

		getHasdoWoDetail(request);
        return new ModelAndView("com/yngrp/wo/woDetail");
	}
	
	/**
	 * 工单打印
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "woPrint")
	public ModelAndView woPrint(HttpServletRequest request) {

		getHasdoWoDetail(request);
		String curTime = DateUtils.formatDate("yyyy.MM.dd HH:mm:ss");
		request.setAttribute("curTime", curTime);
        return new ModelAndView("com/yngrp/wo/woPrint");
	}
	
	/**
	 * 工单详情Tab页查看
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "woDetailTabs")
	public ModelAndView woDetailTabs(HttpServletRequest request) {

		String wo_id = request.getParameter("wo_id");
		request.setAttribute("wo_id", wo_id);
        return new ModelAndView("com/yngrp/wo/woDetailTabs");
	}
	
	/**
	 * 待处理工单Tab页查看
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "todoWoTabs")
	public ModelAndView todoWoTabs(HttpServletRequest request) {
		String todo_id = request.getParameter("todo_id");
		request.setAttribute("todo_id", todo_id);	
		if(StringUtils.isNotBlank(todo_id)){
			TodoWO todoWO = this.systemService.getEntity(TodoWO.class, todo_id);
			todoWO.setIsRead(Constant.WO_ISREAD_1);
			this.systemService.saveOrUpdate(todoWO);
			
		}
		String o_wo_id = request.getParameter("o_wo_id");
		request.setAttribute("o_wo_id", o_wo_id);
		
		String hf = request.getParameter("hf");
		request.setAttribute("hf", hf);
		
        return new ModelAndView("com/yngrp/wo/todoWoTabs");
	}

	
	/**
	 *  待办工单列表页面跳转
	 * 
	 *  @return
	 */
	@RequestMapping(params = "todoWoListR")
	public String todoWoListR(HttpServletRequest request) {
		
		return "com/yngrp/wo/todoWoList";
	}
	
	/***
	 * 部门管理员待办工单列表
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param wo
	 */
	@RequestMapping(params = "todoWoGrid")
	public void todoWoGrid(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(TodoWO.class, dataGrid);
		cq.createAlias("workOrder","workOrder");

		//联系人
        String contactMan = request.getParameter("workOrder.contactMan");
        if(StringUtils.isNotEmpty(contactMan)) {
        	contactMan = contactMan.trim();
        	if(contactMan.lastIndexOf("%")==-1){
        		contactMan = "%"+contactMan + "%";
            }
        	cq.like("workOrder.contactMan", contactMan);
        }
        //处理人员
        String doUsername = request.getParameter("workOrder.doUsername");
        if(StringUtils.isNotEmpty(doUsername)) {
        	doUsername = doUsername.trim();
        	if(doUsername.lastIndexOf("%")==-1){
        		doUsername = "%"+doUsername + "%";
            }
        	cq.like("workOrder.doUsername", doUsername);
        }
        //联系电话
        String contactPhone = request.getParameter("workOrder.contactPhone");
        if(StringUtils.isNotEmpty(contactPhone)) {
        	contactPhone = contactPhone.trim();
        	if(contactPhone.lastIndexOf("%")==-1){
        		contactPhone = "%"+contactPhone + "%";
            }
        	cq.like("workOrder.contactPhone", contactPhone);
        }
        
        TSUser user = ResourceUtil.getSessionUserName();
        String roleCodes = user.getRoleCodes();
        if(StringUtils.isNotEmpty(roleCodes)){
        	//是否为坐席人员
        	if(roleCodes.indexOf(Constant.SEAT_ROLECODE)!=-1){
        		 cq.eq("acUserid", user.getId());
        	}else{
        		 cq.eq("acDeptid", user.getCurrentDepart().getId());
        	}
        }else{
        	cq.eq("acDeptid", user.getCurrentDepart().getId());
        }
       
        cq.notEq("createBy", user.getId());
        
        cq.add();
        this.systemService.getDataGridReturn(cq, true);
        
        List<TodoWO> woList = dataGrid.getResults();
        for(TodoWO todo:woList){
        	if(StringUtils.isBlank(todo.getWorkOrder().getWo95598Id())){
        		todo.getWorkOrder().setWo95598Id(todo.getWorkOrder().getId().toString());
        	}
        	
        	if(todo.getIsRead()!=null && todo.getIsRead().equals(Constant.WO_ISREAD_0)){
        		todo.setIsRead("<font color=red>"+Constant.WO_ISREAD_0+"</font>");
        	}
        }
		TagUtil.datagrid(response, dataGrid);
	}
	
	/**
	 *  待办工单详情页面跳转
	 * 
	 *  @return
	 */
	@RequestMapping(params = "todoWoR")
	public ModelAndView todoWoR(HttpServletRequest request) {
		setWoStateByRole(request);
		getTodoWoDetail(request);
		setOverTime(request);
		
		getWoProcess(request);
		getResponer(request);
		
		isTeamMgr(request);
		isHfwo(request);
		
		return  new ModelAndView("com/yngrp/wo/todoWo");
	}
	
	/**
	 * 判断是否班组用户
	 * @param request
	 */
	private void isTeamMgr(HttpServletRequest request){
		TSUser user = ResourceUtil.getSessionUserName();
        
		Boolean isTeamMgr = user.getRoleCodes().contains(Constant.TEAM_ROLE_CODE);
		request.setAttribute("isTeamMgr", isTeamMgr);
	}
	
	/**
	 * 判断是否回访工单
	 * @param request
	 */
	private void isHfwo(HttpServletRequest request){
		String hf = request.getParameter("hf");
        if(StringUtils.isNotBlank(hf) && hf.equals("y")){
        	request.setAttribute("isHF", true);
        }else{
        	request.setAttribute("isHF", false);
        }
		
	}
	
	/**
	 * 班组责任人集合
	 * @param request
	 */
	private void getResponer(HttpServletRequest request){
		TSUser user = ResourceUtil.getSessionUserName();
        
        List<Responsibler> woResponerList = this.systemService.findHql("from Responsibler where deptId = ?", user.getCurrentDepart().getId());
        request.setAttribute("woResponerList", woResponerList);
	}
	
	//获取临时保存处理的信息
	private void getWoProcess(HttpServletRequest request){
		Long wo_id = null;
		//待办工单
		String todo_id = request.getParameter("todo_id");
		if (StringUtils.isNotBlank(todo_id)) {
			//获取待办工单实体
			TodoWO todoWO = systemService.getEntity(TodoWO.class,todo_id);
			wo_id = todoWO.getWorkOrder().getId();
		}
		
		//回访工单
		String o_wo_id =  request.getParameter("o_wo_id");
		if (StringUtils.isNotBlank(o_wo_id)) {
			wo_id = Long.parseLong(o_wo_id);
		}
				
		TSUser user = ResourceUtil.getSessionUserName();
		List<WorkProcess> processList = systemService.findHql("from WorkProcess where saveState='0' and  workOrder.id=? and createBy = ?",wo_id,user.getId());
		if(processList!=null && processList.size()>0){
			request.setAttribute("saveProcess",processList.get(0));
		}
	}
	
	/**
	 * 设置工单处理时限
	 * @param request
	 */
	private void setOverTime(HttpServletRequest request){
		//待办工单
		String todo_id = request.getParameter("todo_id");
		if (StringUtil.isNotEmpty(todo_id)) {
			//获取待办工单实体
			TodoWO todoWO = systemService.getEntity(TodoWO.class,todo_id);
			Long wo_id = todoWO.getWorkOrder().getId();
			WorkOrder wo = systemService.getEntity(WorkOrder.class,wo_id);
			//处理时限
			String overTime = workOrderService.callOverTime(wo.getWoType());
			request.setAttribute("overTime", overTime);
		}
		
	}
	
	/**
	 * 根据待办工单编号获取工单详情
	 * @param request
	 */
	private void getTodoWoDetail(HttpServletRequest request){
		//待办工单
		String todo_id = request.getParameter("todo_id");
		//回访工单
		String o_wo_id =  request.getParameter("o_wo_id");
		
        WorkOrder wo = new WorkOrder();
        Long wo_id = null;
        List<WorkProcess> processList = new ArrayList<WorkProcess>();
        
        //关联工单信息
        List<WorkAsso> assoList = new ArrayList<WorkAsso>();
        //第近一次处理工单 
        WorkProcess lastWp = null;
		if (StringUtil.isNotEmpty(todo_id)) {
			//获取待办工单实体
			TodoWO todoWO = systemService.getEntity(TodoWO.class,todo_id);
			wo_id = todoWO.getWorkOrder().getId();
		}else if (StringUtil.isNotEmpty(o_wo_id)) {
			wo_id = Long.parseLong(o_wo_id);
			
		}
		
		if(wo_id!=null){
			//获取工单基本信息
			wo = systemService.getEntity(WorkOrder.class,wo_id);
			wo.setTodoId(todo_id);
			
			//获取工单办理信息
			processList = systemService.findHql("from WorkProcess where   workOrder=? order by createDatetime",wo);
			if(processList!=null && processList.size()>0){
				lastWp = processList.get(processList.size()-1);
			}
			
			//获取关联工单信息
			assoList = systemService.findHql("from WorkAsso where mainWoid = ?",wo_id);
		
		}
		request.setAttribute("wo", wo);
		request.setAttribute("lastWp", lastWp);
		request.setAttribute("processList", processList);
		request.setAttribute("assoList", assoList);
		
		//设置工单用时情况
		if(wo_id!=null){
			try{
				setWoUserTime(request,wo);
			}catch(Exception ex){
				ex.printStackTrace();
			}
		}
		
		
		//默认显示工单状态
		//request.setAttribute("defaultState", Constant.S00);
		TSUser user = ResourceUtil.getSessionUserName();
		//如果用户是优质管理员或增值管理员或坐席人员
		if(user.getRoleCodes().contains(Constant.SEAT_ROLE_MGR_CODE)||user.getRoleCodes().contains(Constant.SEAT_ROLECODE)){
			if(wo.getWoState().equals(Constant.S02)){//如果是提交审核
				request.setAttribute("defaultState", Constant.S01);//办结
			}else if(wo.getWoState().equals(Constant.S04)){//退单
				request.setAttribute("defaultState", Constant.S03);//派发
			}
		}
	}
	
	//设置工单用时情况
	private void setWoUserTime(HttpServletRequest request,WorkOrder wo) throws Exception{
		//计算工单用时
		Map<String,Object> m = systemService.findOneForJdbc("SELECT SUM(usehours) userhours FROM yl_wo_process  WHERE wo_operation!='"+Constant.S00+"' and wo_id=?", wo.getId());
		if(null!=m.get("userhours")){
			Float userHours = Float.valueOf(m.get("userhours").toString());
			request.setAttribute("USERHOURS", userHours);
		}else{
			request.setAttribute("USERHOURS", "1");
		}
		
		//工单办结截止时间 
		if(StringUtils.isNotBlank(wo.getOverTime())){
			String overtime = wo.getOverTime();
			Date oDate = DateUtils.parseDate(overtime,"yyyy-MM-dd HH:mm:ss");
			
			//如果 工单归档或办结
			if(wo.getWoState().equals(Constant.S01) || wo.getWoState().equals(Constant.S00)){
				//工单创建时间
				Date  cDate = wo.getCreateDatetime();
				//相隔小时数
				long difhours = (oDate.getTime()-cDate.getTime())/(60*60*1000);
				
				request.setAttribute("REMAINTIME", difhours+" 小时");
				request.setAttribute("REMAINTITLE", "剩余时长");
			}else{
				
				//当前时间
				Date curDate = new Date();
				//相隔小时数
				long difhours = (oDate.getTime()-curDate.getTime())/(60*60*1000); 
	//			long day = difhours/24;
	//			long hours = difhours%24;
	//			String str = "";
	//			if(day>0){
	//				str = "剩余 "+day+" 天 " +hours+" 小时";
	//			}else if(day==0){
	//				if(hours>=0){
	//					str = "剩余 "+hours+" 小时";
	//				}else{
	//					str = "滞后 "+Math.abs(hours)+" 小时";
	//				}
	//			}else{
	//				str = "滞后 "+Math.abs(day)+" 天 " +Math.abs(hours)+" 小时";
	//			};
				String str = difhours+" 小时";
				if(difhours<0){
					str += " (滞后)";
				}
				request.setAttribute("REMAINTIME", str);
				request.setAttribute("REMAINTITLE", "剩余时长");
			}
		}
	}
	
	public static void main(String[] args){
		long difhours = -14;
		long m = difhours/24;
		long n = difhours%24;
		System.out.println(m);  
		System.out.println(n);  
		
	}
	
	/**
	 * 待办工单处理意见保存
	 * 
	 * @param wo
	 * @return
	 */
	@RequestMapping(params = "saveProcessWO")
	@ResponseBody
	public AjaxJson saveProcessWO(WorkOrder wo, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		
		try{
			if(wo.getSaveState().equals("1")){
				message = "提交成功！";
			}else{
				message = "保存成功！";
			}
			workOrderService.saveProcessWO(wo);
			systemService.addLog(message, Globals.Log_Type_INSERT,Globals.Log_Leavel_INFO);
			
			j.setMsg(message);
		}catch(Exception ex){
			message = "提交失败，请联系系统管理员！";
			systemService.addLog(message, Globals.Log_Type_INSERT,Globals.Log_Leavel_ERROR);
			j.setMsg(message);
		}

		return j;
	}
	
	
	/**
	 *  已办工单列表页面跳转
	 * 
	 *  @return
	 */
	@RequestMapping(params = "hasdoWoListR")
	public String hasdoWoListR(HttpServletRequest request) {
		
		return "com/yngrp/wo/hasdoWoList";
	}
	
	/***
	 * 部门管理员已办工单列表
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param wo
	 */
	@RequestMapping(params = "hasdoWoGrid")
	public void hasdoWoGrid(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
CriteriaQuery cq = new CriteriaQuery(WorkOrder.class, dataGrid);
		
		//字段选项
		String pmd = request.getParameter("pmd");
		//字段值
		String pmv = request.getParameter("pmv");
		//工单来源
		String woSrc = request.getParameter("woSrc");
		//开始日期
		String startDate = request.getParameter("startDate");
		//结束日期
		String endDate = request.getParameter("endDate");

		
        if(StringUtils.isNotEmpty(pmv)) {
        	pmv = pmv.trim();
        	if(pmd.equals("id")){
        		cq.add(Restrictions.or(Restrictions.eq("id",Long.parseLong(pmv)),
        				               Restrictions.eq("wo95598Id",pmv)));

        	}else{
        		if(pmv.lastIndexOf("%")==-1){
            		pmv = "%"+ pmv + "%";
                }
        		cq.like(pmd, pmv);
        	}
        }
        
        //工单来源
        if(StringUtils.isNotEmpty(woSrc)) {
        	cq.eq("woSrc", woSrc);
        }
        
        //开始日期
        if(StringUtils.isNotEmpty(startDate)) {
        	Date startDt = null;
			try {
				startDt = DateUtils.parseDate(startDate, "yyyy-MM-dd");
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	cq.gt("createDatetime", startDt);
        }
        //结束日期
        if(StringUtils.isNotEmpty(endDate)) {
        	Date endDt = null;
			try {
				endDt = DateUtils.parseDate(endDate, "yyyy-MM-dd");
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	cq.lt("createDatetime", endDt);
        }
        
        TSUser user = ResourceUtil.getSessionUserName();
        CriteriaQuery subCq = new CriteriaQuery(WorkProcess.class);
        subCq.setProjection(Property.forName("workOrder.id"));
        subCq.eq("createDepartmentid", user.getCurrentDepart().getId());
        subCq.add();

        cq.add(Property.forName("id").in(subCq.getDetachedCriteria()));
              
        cq.add();
        this.systemService.getDataGridReturn(cq, true);
        
        set95598WorkOrder(dataGrid);        
		TagUtil.datagrid(response, dataGrid);
	}
	
	//设置95598工单编号
	private void set95598WorkOrder(DataGrid dataGrid){
		List<WorkOrder> woList = dataGrid.getResults();
        for(WorkOrder wo:woList){
        	if(StringUtils.isBlank(wo.getWo95598Id())){
        		wo.setWo95598Id(wo.getId().toString());
        	}
        }
	}
	
	
	/**
	 *  已办工单详情页面跳转
	 * 
	 *  @return
	 */
	@RequestMapping(params = "hasdoWoR")
	public ModelAndView hasdoWoR(HttpServletRequest request) {
		
		getHasdoWoDetail(request);
		return  new ModelAndView("com/yngrp/wo/hasdoWoR");
	}
	
	/**
	 * 根据工单编号获取工单详情
	 * @param request
	 */
	private void getHasdoWoDetail(HttpServletRequest request){
		String wo_id = request.getParameter("wo_id");
		if(StringUtils.isBlank(wo_id)){
			String todo_id = request.getParameter("todo_id");
			//获取待办工单实体
			TodoWO todoWO = systemService.getEntity(TodoWO.class,todo_id);
			wo_id = todoWO.getWorkOrder().getId().toString();
		}
        WorkOrder wo = new WorkOrder();
        //工单处理信息
        List<WorkProcess> processList = new ArrayList<WorkProcess>();
        //关联工单信息
        List<WorkAsso> assoList = new ArrayList<WorkAsso>();
        //最新一次处理意见
        WorkProcess lastWp = null;
		if (StringUtil.isNotEmpty(wo_id)) {			
			//获取工单基本信息
			wo = systemService.getEntity(WorkOrder.class,Long.parseLong(wo_id));
			
			//获取工单办理信息
			processList = systemService.findHql("from WorkProcess where   workOrder.id=? order by createDatetime",wo.getId());
			
			if(processList!=null && processList.size()>0){
				lastWp = processList.get(processList.size()-1);
				
				//归档工单
				if(lastWp.getWorkOrder().getWoState().equals(Constant.S00)){
					request.setAttribute("archiveWo", lastWp);
				}
				
				//办结工单
				if(lastWp.getWorkOrder().getWoState().equals(Constant.S01)){
					request.setAttribute("overWo", lastWp);
				}
			}
		
			//获取关联工单信息
			assoList = systemService.findHql("from WorkAsso where mainWoid = ?",Long.parseLong(wo_id));
		}
		request.setAttribute("wo", wo);
		request.setAttribute("lastWp", lastWp);
		request.setAttribute("processList", processList);
		request.setAttribute("assoList", assoList);
		
		//设置工单用时情况
		if(wo_id!=null){
			try{
				setWoUserTime(request,wo);
			}catch(Exception ex){
				ex.printStackTrace();
			}
		}
	}
	
	
	/**
	 *  综合查询列表页面跳转
	 * 
	 *  @return
	 */
	@RequestMapping(params = "synQueryListR")
	public String synQueryListR(HttpServletRequest request) {
		//设置工单状态
		setTsTypeGroup(request);
		
		return "com/yngrp/wo/synQueryList";
	}
	
	/***
	 * 综合查询工单列表
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param wo
	 */
	@RequestMapping(params = "synQueryListGrid")
	public void synQueryListGrid(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(WorkOrder.class, dataGrid);
		
		//字段选项
		String pmd = request.getParameter("pmd");
		//字段值
		String pmv = request.getParameter("pmv");
		//工单状态
		//String woState = request.getParameter("woState");
		//工单来源
		String woSrc = request.getParameter("woSrc");
		//办理部门
		//String zOrgIds = request.getParameter("zOrgIds");
		//开始日期
		String startDate = request.getParameter("startDate");
		//结束日期
		String endDate = request.getParameter("endDate");

		
        if(StringUtils.isNotEmpty(pmv)) {
        	pmv = pmv.trim();
        	if(pmd.equals("id")){
        		cq.add(Restrictions.or(Restrictions.eq("id",Long.parseLong(pmv)),
        				               Restrictions.eq("wo95598Id",pmv)));

        	}else{
        		if(pmv.lastIndexOf("%")==-1){
            		pmv = "%"+ pmv + "%";
                }
        		cq.like(pmd, pmv);
        	}
        }
        
        //工单来源
        if(StringUtils.isNotEmpty(woSrc)) {
        	cq.eq("woSrc", woSrc);
        }
        
        //开始日期
        if(StringUtils.isNotEmpty(startDate)) {
        	Date startDt = null;
			try {
				startDt = DateUtils.parseDate(startDate, "yyyy-MM-dd");
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	cq.gt("createDatetime", startDt);
        }
        //结束日期
        if(StringUtils.isNotEmpty(endDate)) {
        	Date endDt = null;
			try {
				endDt = DateUtils.parseDate(endDate, "yyyy-MM-dd");
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	cq.lt("createDatetime", endDt);
        }
        
      /*if(StringUtils.isNotEmpty(woState)) {
        	cq.eq("woState", woState);
        }
        
        if(StringUtils.isNotEmpty(zOrgIds)) {
        	zOrgIds = zOrgIds.substring(0, zOrgIds.lastIndexOf(","));
        	String[] depatIds = zOrgIds.split(",");
        	//cq.in("createDepartmentid", depatIds);
        	
        	CriteriaQuery subCq = new CriteriaQuery(WorkProcess.class);
            subCq.setProjection(Property.forName("workOrder.id"));
            subCq.in("createDepartmentid", depatIds);
            subCq.add();

            cq.add(Property.forName("id").in(subCq.getDetachedCriteria()));
        }*/
        
              
        cq.add();
        this.systemService.getDataGridReturn(cq, true);
        
        set95598WorkOrder(dataGrid); 
		TagUtil.datagrid(response, dataGrid);
	}
	
	/**
	 * 设置工单状态集合
	 * @param request
	 */
	private void setTsTypeGroup(HttpServletRequest request){
		List<TSType> typeList = workOrderService.getTsTypeByGroupName(Constant.WOSTATE);
		request.setAttribute("typeList", typeList);
	}
	
	/**
	 *  工单详情导出excel
	 * 
	 *  @return
	 * @throws IOException 
	 */	
	@RequestMapping(params = "exportWoXls")
	public String exportWoXls(HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {	
		String wo_id = request.getParameter("wo_id");
        WorkOrder wo = new WorkOrder();
        List<WorkProcess> processList = new ArrayList<WorkProcess>();
        Map<String,Object> woMap = new HashMap<String,Object>();
		if(StringUtils.isNotBlank(wo_id)) {			
			//获取工单基本信息
			wo = systemService.getEntity(WorkOrder.class,Long.parseLong(wo_id));
			if(StringUtils.isNotBlank(wo.getWo95598Id())){
				woMap.put("wo_id", wo.getWo95598Id());
			}else{
				woMap.put("wo_id", wo.getId());
			}
			woMap.put("customerNo", wo.getCustomerNo());
			woMap.put("customerName", wo.getCustomerName());
			woMap.put("contactPhone2", wo.getContactPhone2());
			woMap.put("contactMan", wo.getContactMan());
			woMap.put("contactPhone", wo.getContactPhone());
			woMap.put("contactAddress", wo.getContactAddress());
			
			woMap.put("woSrcDesc", wo.getWoSrcDesc());
			woMap.put("woTypeDesc", wo.getWoTypeDesc());
			woMap.put("woContent", wo.getWoContent());
			woMap.put("createRealname", wo.getCreateRealname());
			woMap.put("createDatetime", DateUtils.formatDate(wo.getCreateDatetime(), "yyyy.MM.dd HH:mm:ss"));
			
			//获取工单办理信息
			processList = systemService.findHql("from WorkProcess where workOrder=? order by createDatetime",wo);
			StringBuffer allOpinion = new StringBuffer();
			for(WorkProcess wp: processList){
				allOpinion.append(wp.getCreateDepartmentname()+"   "+wp.getCreateRealname()+"   【"+wp.getWoOperadesc()+"】          "+DateUtils.formatDate(wp.getCreateDatetime(), "yyyy.MM.dd HH:mm:ss"));
				allOpinion.append("\r\n"+wp.getWoOpinion());
				allOpinion.append("\r\n--------------------------------------------------------------------------------------\r\n");
			}
			woMap.put("allOpinion", allOpinion);
			
			
		}
		
        modelMap.put(TemplateExcelConstants.FILE_NAME,wo_id+"工单详情");
        modelMap.put(TemplateExcelConstants.PARAMS,new TemplateExportParams("export/template/exportWo.xls",0));
        modelMap.put(TemplateExcelConstants.MAP_DATA,woMap);
        return TemplateExcelConstants.JEECG_TEMPLATE_EXCEL_VIEW;
        
	}
	
	/**
	 * 工单处理详情
	 * 
	 * @param role
	 * @return
	 */
	@RequestMapping(params = "showWoProcessDetail")
	@ResponseBody
	public AjaxJson showWoProcessDetail(HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		String process_id = request.getParameter("process_id");
	
		WorkProcess wp = systemService.get(WorkProcess.class, process_id);	
		
        j.setObj(wp);
		j.setMsg(message);
		j.setSuccess(true);
		return j;
	}
	
	/**
	 *  工单关联设置页面跳转
	 * 
	 *  @return
	 */
	@RequestMapping(params = "assoWoR")
	public String assoWoR(HttpServletRequest request) {
		String wo_id = request.getParameter("wo_id");
		request.setAttribute("wo_id", wo_id);
		
		return "com/yngrp/wo/assoWo";
	}
	
	/**
	 * 保存关联工单
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "doAddAssoWo")
	@ResponseBody
	public AjaxJson doAddAssoWo(HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		
		try{
			//主工单编号
			String mainWoid = request.getParameter("wo_id");
			//关联工单编号
			String asWoIds = request.getParameter("asWoIds");
			
			message = "提交成功！";
			workOrderService.saveAssoWO(mainWoid,asWoIds);
			systemService.addLog(message, Globals.Log_Type_INSERT,Globals.Log_Leavel_INFO);
			
			j.setMsg(message);
		}catch(Exception ex){
			message = "提交失败，请联系系统管理员！";
			systemService.addLog(message, Globals.Log_Type_INSERT,Globals.Log_Leavel_INFO);
			j.setMsg(message);
		}

		return j;
	}
	
	
	/**
	 *  已办结工单回访页面跳转
	 * 
	 *  @return
	 */
	@RequestMapping(params = "woOverR")
	public String woOverR(HttpServletRequest request) {
		
		return "com/yngrp/wo/overWoList";
	}
	
	/***
	 * 已办结工单列表
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param wo
	 */
	@RequestMapping(params = "woOverListGrid")
	public void woOverListGrid(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid, WorkOrder wo) {
		CriteriaQuery cq = new CriteriaQuery(WorkOrder.class, dataGrid);
		
		//客户编号
	/*	Long wo_id = wo.getId();
        if(wo_id!=null) { 
        	 
        	cq.eq("id", wo_id);
        }*/
		
		//联系人
        String contactMan = wo.getContactMan();
        if(StringUtils.isNotEmpty(contactMan)) {
        	contactMan = contactMan.trim();
        	if(contactMan.lastIndexOf("%")==-1){
        		contactMan = "%"+contactMan + "%";
            }
        	cq.like("contactMan", contactMan);
        }
        //处理人
        String doUsername = wo.getDoUsername();
        if(StringUtils.isNotEmpty(doUsername)) {
        	doUsername = doUsername.trim();
        	if(doUsername.lastIndexOf("%")==-1){
        		doUsername = "%"+doUsername + "%";
            }
        	cq.like("doUsername", doUsername);
        }
        //联系电话
        String contactPhone = wo.getContactPhone();
        if(StringUtils.isNotEmpty(contactPhone)) {
        	contactPhone = contactPhone.trim();
        	if(contactPhone.lastIndexOf("%")==-1){
        		contactPhone = "%"+contactPhone + "%";
            }
        	cq.like("contactPhone", contactPhone);
        }
 
        cq.eq("woState", Constant.S01);   //只取已办结工单
        cq.eq("woSrc", Constant.A02);  //只取增值服务工单
        cq.add();
        this.systemService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	
	
	
	/**
	 *  工单类型维护页面跳转
	 * 
	 *  @return
	 */
	@RequestMapping(params = "woTypeListR")
	public String woTypeListR(HttpServletRequest request) {
		
		return "com/yngrp/wo/woTypeList";
	}
	
	/***
	 * 工单类型维护列表
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param woType
	 */
	@RequestMapping(params = "woTypeGrid")
	public void woTypeGrid(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid, WoType woType) {
		CriteriaQuery cq = new CriteriaQuery(WoType.class, dataGrid);
		
		//工单类型名称
        String typeName = woType.getTypeName();
        if(StringUtils.isNotEmpty(typeName)) {
        	typeName = typeName.trim();
        	if(typeName.lastIndexOf("%")==-1){
        		typeName = "%"+typeName + "%";
            }
        	cq.like("typeName", typeName);
        }
 
        cq.add();
        this.systemService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	
	/**
	 * 添加工单类型维护页面跳转
	 *
	 * @return
	 */
	@RequestMapping(params = "aouWoType")
	public ModelAndView aouWoType(WoType woType, HttpServletRequest req) {
		if (woType.getId() != null) {
			woType = systemService.getEntity(WoType.class, woType.getId());
			req.setAttribute("wo_type", woType);
		}
		
		return new ModelAndView("com/yngrp/wo/addWoType");
	}
	
	/**
	 * 保存工单类型
	 * 
	 * @param woType
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "saveWoType")
	@ResponseBody
	public AjaxJson saveWoType(WoType woType, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		String platCode = woType.getPlatCode();
		String platform = "";
		if(StringUtil.isNotEmpty(platCode)){
			if(platCode.equals("A01")){
				platform = "95598工单";
			}else if(platCode.equals("A02")){
				platform = "增值服务";
			}
			woType.setPlatform(platform);
		}
		
		if (StringUtil.isNotEmpty(woType.getId())) {
			systemService.updateEntitie(woType);
			
			message = "更新工单类型【"+woType.getTypeName()+"】成功";
			systemService.addLog(message, Globals.Log_Leavel_INFO, Globals.Log_Type_UPDATE);
		} else {			
			systemService.save(woType);
			
			message = "添加工单类型【"+woType.getTypeName()+"】成功";
			systemService.addLog(message, Globals.Log_Leavel_INFO, Globals.Log_Type_INSERT);
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 删除工单类型
	 *
	 * @return
	 */
	@RequestMapping(params = "delWoType")
	@ResponseBody
	public AjaxJson delWoType(WoType woType, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
	
		woType = systemService.getEntity(WoType.class, woType.getId());
		message = "删除工单类型【"+woType.getTypeName()+"】成功";
		systemService.delete(woType);
		
		systemService.addLog(message, Globals.Log_Leavel_INFO, Globals.Log_Type_DEL);
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 计算工单办结截止时间
	 *
	 * @return
	 */
	@RequestMapping(params = "callOverTime")
	@ResponseBody
	public AjaxJson callOverTime(HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		String typeCode = request.getParameter("typeCode");
	    message = workOrderService.callOverTime(typeCode);
		j.setSuccess(true);
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 根据工单来源获取工单类型
	 *
	 * @return
	 */
	@RequestMapping(params = "selectType")
	@ResponseBody
	public AjaxJson selectType(HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		String woSrc = request.getParameter("woSrc");
	   // message = workOrderService.callOverTime(typeCode);
		List<WoType> typeLst = this.systemService.findHql("from WoType where platCode = ? and status='启用' order by sortNo", woSrc);
		j.setObj(typeLst);
		j.setSuccess(true);
		j.setMsg(message);
		return j;
	}
	
	/**
	 *  节假日维护页面跳转
	 * 
	 *  @return
	 */
	@RequestMapping(params = "toHolidayList")
	public String toHolidayList(HttpServletRequest request) {
		
		return "com/yngrp/wo/woHolidayList";
	}
	
	/***
	 * 节假日列表
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param woType
	 */
	@RequestMapping(params = "woHolidayGrid")
	public void woHolidayGrid(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid, Holiday holiday) {
		CriteriaQuery cq = new CriteriaQuery(Holiday.class, dataGrid);
		
		//节假日期
        String hDate = holiday.gethDate();
        if(StringUtils.isNotEmpty(hDate)) {
        	hDate = hDate.trim();
        	if(hDate.lastIndexOf("%")==-1){
        		hDate = "%"+hDate + "%";
            }
        	cq.like("hDate", hDate);
        }
        
        //节假日名称
        String hName = holiday.gethName();
        if(StringUtils.isNotEmpty(hName)) {
        	hName = hName.trim();
        	if(hName.lastIndexOf("%")==-1){
        		hName = "%"+hName + "%";
            }
        	cq.like("hName", hName);
        }
 
        cq.add();
        this.systemService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	
	/**
	 * 添加节假日维护页面跳转
	 * @param holiday
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "aouHoliday")
	public ModelAndView aouHoliday(Holiday holiday, HttpServletRequest req) {
		if (holiday.getId() != null) {
			holiday = systemService.getEntity(Holiday.class, holiday.getId());
			req.setAttribute("wo_holiday", holiday);
		}
		
		return new ModelAndView("com/yngrp/wo/addHoliday");
	}
	
	/**
	 * 保存节假日
	 * 
	 * @param holiday
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "saveHoliday")
	@ResponseBody
	public AjaxJson saveHoliday(Holiday holiday, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		if (StringUtil.isNotEmpty(holiday.getId())) {
			systemService.updateEntitie(holiday);
			
			message = "更新节假日【"+holiday.gethName()+"】成功";
			systemService.addLog(message, Globals.Log_Leavel_INFO, Globals.Log_Type_UPDATE);
		} else {			
			systemService.save(holiday);
			
			message = "添加节假日【"+holiday.gethName()+"】成功";
			systemService.addLog(message, Globals.Log_Leavel_INFO, Globals.Log_Type_INSERT);
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 删除节假日
	 *
	 * @return
	 */
	@RequestMapping(params = "delHoliday")
	@ResponseBody
	public AjaxJson delHoliday(Holiday holiday, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
	
		holiday = systemService.getEntity(Holiday.class, holiday.getId());
		message = "删除节假日【"+holiday.gethName()+"】成功";
		systemService.delete(holiday);
		
		systemService.addLog(message, Globals.Log_Leavel_INFO, Globals.Log_Type_DEL);
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 责任人维护页面跳转
	 * 
	 *  @return
	 */
	@RequestMapping(params = "toResponsiblerList")
	public String toResponsiblerList(HttpServletRequest request) {
		
		return "com/yngrp/wo/woResponiblerList";
	}
	
	/***
	 * 责任人列表
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param responsibler
	 */
	@RequestMapping(params = "woResponerGrid")
	public void woResponerGrid(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid, Responsibler responsibler) {
		CriteriaQuery cq = new CriteriaQuery(Responsibler.class, dataGrid);
		
		//责任人名称
        String responerName = responsibler.getResponerName();
        if(StringUtils.isNotEmpty(responerName)) {
        	responerName = responerName.trim();
        	if(responerName.lastIndexOf("%")==-1){
        		responerName = "%"+responerName + "%";
            }
        	cq.like("responerName", responerName);
        }
        //班组名称
        String deptName = responsibler.getDeptName();
        if(StringUtils.isNotEmpty(deptName)) {
        	deptName = deptName.trim();
        	if(deptName.lastIndexOf("%")==-1){
        		deptName = "%"+deptName + "%";
            }
        	cq.like("deptName", deptName);
        }
        
 
        cq.add();
        this.systemService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	
	
	/**
	 * 添加责任人维护页面跳转
	 * @param holiday
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "aouResponer")
	public ModelAndView aouResponer(Responsibler responsibler, HttpServletRequest req) {
		if (responsibler.getId() != null) {
			responsibler = systemService.getEntity(Responsibler.class, responsibler.getId());
			req.setAttribute("wo_responer", responsibler);
		}
		
		return new ModelAndView("com/yngrp/wo/addResponer");
	}
	

	/**
	 * 保存责任人
	 * 
	 * @param responsibler
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "saveResponer")
	@ResponseBody
	public AjaxJson saveResponer(Responsibler responsibler, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		if (StringUtil.isNotEmpty(responsibler.getId())) {
			systemService.updateEntitie(responsibler);
			
			message = "更新责任人【"+responsibler.getResponerName()+"】成功";
			systemService.addLog(message, Globals.Log_Leavel_INFO, Globals.Log_Type_UPDATE);
		} else {			
			systemService.save(responsibler);
			
			message = "添加责任人【"+responsibler.getResponerName()+"】成功";
			systemService.addLog(message, Globals.Log_Leavel_INFO, Globals.Log_Type_INSERT);
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 删除责任人
	 *
	 * @return
	 */
	@RequestMapping(params = "delResponer")
	@ResponseBody
	public AjaxJson delResponer(Responsibler responsibler, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
	
		responsibler = systemService.getEntity(Responsibler.class, responsibler.getId());
		message = "删除责任人【"+responsibler.getResponerName()+"】成功";
		systemService.delete(responsibler);
		
		systemService.addLog(message, Globals.Log_Leavel_INFO, Globals.Log_Type_DEL);
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 读取待处理工单数
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "readTodoWo")
	@ResponseBody
	public AjaxJson readTodoWo(HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		
		try{
			Map<String,Object> map = null;
			TSUser user = ResourceUtil.getSessionUserName(); 
	        String roleCodes = user.getRoleCodes();
	        if(StringUtils.isNotEmpty(roleCodes)){
	        	//是否为坐席人员
	        	if(roleCodes.indexOf(Constant.SEAT_ROLECODE)!=-1){
	        		 map = systemService.findOneForJdbc("select count(1) cnt from yl_wo_todo where acUserid = ?", user.getId());
	        	}else{
	        		 map = systemService.findOneForJdbc("select count(1) cnt from yl_wo_todo where ac_dept_id = ?", user.getCurrentDepart().getId());
	        	}
	        }else{
	        	map = systemService.findOneForJdbc("select count(1) cnt from yl_wo_todo where ac_dept_id = ?", user.getCurrentDepart().getId());
	        }
	        
			
			j.setSuccess(true);
			message = map.get("cnt").toString();
			j.setMsg(message);
		}catch(Exception ex){
			j.setSuccess(false);
			j.setMsg(message);
		}

		return j;
	}

}
